package com.asset.dispoal.poi.documentation;

import com.asset.dispoal.poi.tools.api.IToolService;
import com.asset.dispoal.poi.tools.dto.CivilComplaintRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.io.IOUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * @description:
 * @author: yf
 * @date: 2023-07-12 15:53:23
 */
@RestController
@Api(value = "工具管理", tags = "工具管理")
@RequestMapping("poi/tools")
public class ToolController {

    @Autowired
    private IToolService toolService;

    @ApiOperation(value = "民事起诉状生成", notes = "民事起诉状生成")
    @PostMapping(value = "/civilComplaint")
    public ResponseEntity<ByteArrayResource> downloadDocument(CivilComplaintRequest request) {
        Result complaint = toolService.createComplaint(request);
        if (complaint.getData() != null) {
            try {
                InputStream inputStream = new FileInputStream((String) complaint.getData());
                byte[] data = IOUtil.toByteArray(inputStream);
                ByteArrayResource resource = new ByteArrayResource(data);
                return ResponseEntity.ok()
                        .contentLength(data.length)
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + request.getDownLoadFileName() + "\"")
                        .contentType(MediaType.parseMediaType("application/octet-stream"))
                        .body(resource);
            } catch (FileNotFoundException e) {
                throw new BusinessException(500, "找不到压缩文件");
            } catch (IOException e) {
                throw new BusinessException(500, "系统异常");
            }
        }
        return null;
    }
}
